#include "spinboxdelegate.h"

#include <QDebug>
#include <QKeyEvent>
#include <QCoreApplication>

SpinBoxDelegate::SpinBoxDelegate(QObject *parent, int decimals, bool withCurrency)
    : QItemDelegate(parent)
{
    m_decimals=decimals;
    m_withCurrency=withCurrency;
}

QWidget *SpinBoxDelegate::createEditor(QWidget *parent,
                                       const QStyleOptionViewItem &/* option */,
                                       const QModelIndex &/* index */) const
{
    cs8DoubleSpinBox *editor = new cs8DoubleSpinBox(parent);
    editor->setMinimum(0);
    editor->setMaximum(9999);
    editor->setDecimals (m_decimals);
    editor->setButtonSymbols (QDoubleSpinBox::NoButtons);
    editor->setSingleStep (0);
    connect(editor,SIGNAL(keypress(int)),this,SLOT(slotKeyPressed(int)));
    if (m_withCurrency)
        editor->setSuffix (trUtf8 ("€"));
    return editor;
}

void SpinBoxDelegate::setEditorData(QWidget *editor,
                                    const QModelIndex &index) const
{
    QString data=index.model()->data(index, Qt::EditRole).toString();
    data.remove(trUtf8 ("€"));
    double value = data.toDouble();

    QDoubleSpinBox *spinBox = static_cast<QDoubleSpinBox*>(editor);
    spinBox->setValue(value);
}

void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                   const QModelIndex &index) const
{
    cs8DoubleSpinBox *spinBox = static_cast<cs8DoubleSpinBox*>(editor);
    spinBox->interpretText();
    QString value = QString("%1%2")
            .arg(spinBox->value(),0, 'f', m_decimals)
            .arg(m_withCurrency ? trUtf8 ("€"):"");

    model->setData(index, value, Qt::EditRole);
}

void SpinBoxDelegate::updateEditorGeometry(QWidget *editor,
                                           const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
    editor->setGeometry(option.rect);
}

void SpinBoxDelegate::slotKeyPressed(int key)
{
    qDebug() << "key signal received:" << key << "posting to "<< parent ()->objectName ();
    QKeyEvent *event= new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier);
    QCoreApplication::postEvent(parent(),event);
}

